package com.example.myapplication.utils

import android.util.Base64
import java.nio.charset.StandardCharsets
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
import kotlin.jvm.Throws
import kotlin.text.toByteArray


object AES256GCMUtil {
    private const val ALGORITHM = "AES/GCM/NoPadding"
    private const val IV_LENGTH = 12
    private const val TAG_LENGTH = 128

    @Throws(Exception::class)
    fun decrypt(cipherText: String?, keyStr: String): String {
        try {
            val key: SecretKey = SecretKeySpec(keyStr.toByteArray(StandardCharsets.UTF_8), "AES")
            val decoded = Base64.decode(cipherText, Base64.NO_WRAP)

            val iv = ByteArray(IV_LENGTH)
            val cipherBytes = ByteArray(decoded.size - IV_LENGTH)
            System.arraycopy(decoded, 0, iv, 0, iv.size)
            System.arraycopy(decoded, iv.size, cipherBytes, 0, cipherBytes.size)

            val cipher = Cipher.getInstance(ALGORITHM)
            val spec = GCMParameterSpec(TAG_LENGTH, iv)
            cipher.init(Cipher.DECRYPT_MODE, key, spec)

            val plaintext = cipher.doFinal(cipherBytes)

            return String(plaintext, StandardCharsets.UTF_8)
        } catch (e: Exception) {
            return "{}"
        }
    }
}
